package com.example.websocket.another.service;

import com.example.websocket.another.constant.UserSexEnum;
import com.example.websocket.another.entity.UserEntity;
import com.example.websocket.another.mapper.UserMapper;
import com.example.websocket.another.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名获取token
     *
     * @param username
     * @return
     */
    public Object getUserIdByName(String username) {
        UserEntity userEntity = userMapper.getOneByName(username);
        if (userEntity == null) {
            userEntity = UserEntity.builder().userName(username).passWord("default").userSex(UserSexEnum.MAN).build();
            userMapper.insert(userEntity);
        }
        String token = JwtUtil.generateToken(userEntity);
        Map<String, Object> data = new HashMap<>(4);
        data.put("token", token);
        data.put("userId", userEntity.getId());
        return data;
    }

    public UserEntity getOne(long l) {
        return userMapper.getOne(l);
    }

    public String getUserName(String userId) {
        return userMapper.getOne(Long.parseLong(userId)).getUserName();
    }
}
